

from rest_framework.views import  APIView
from rest_framework.response import Response
from api.utils.auth import LoginAuth
from api.models import *
from api.utils.response import BaseResponse
from api.utils.exceptions import CommonExcetpion
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
import redis
import json
import datetime

cache = redis.Redis(decode_responses=True)

class AccountView(APIView):
    authentication_classes = [LoginAuth]

    def get_coupon_dict(self,request,course_id=None):

        now = datetime.datetime.now()
        coupon_record_list = CouponRecord.objects.filter(
            account=request.user,
            coupon__content_type=8,
            coupon__object_id=course_id,
            status=0,
            coupon__valid_begin_date__lte=now,
            coupon__valid_end_date__gte=now,
        )
        print("coupon_record_list:", coupon_record_list)
        coupons = {}
        for coupon_record in coupon_record_list:
            coupons[coupon_record.pk] = {
                "name": coupon_record.coupon.name,
                "coupon_type": coupon_record.coupon.coupon_type,
                "money_equivalent_value": coupon_record.coupon.money_equivalent_value,
                "off_percent": coupon_record.coupon.off_percent,
                "minimum_consume": coupon_record.coupon.minimum_consume
            }
        return coupons

    def post(self,request):
        """
        状态码：
            1000 成功
            1001 课程不存在

        模拟请求数据
        {
        "course_id_list": [1,2],
        }
        :param request:
        :return:
        """
        # 1 获取请求数据
        course_id_list = request.data.get("course_id_list")
        user_id = request.user.pk

        res = BaseResponse()

        try:
            for course_id in course_id_list:    # 结算情况： 1.直接购买  2.购物结算

                # 结算key
                account_key = settings.ACCOUNT_KEY%(user_id,course_id)
                # 结算字典
                account_val = {}

                # 获取课程基本信息
                shoppingcart_key = settings.SHOPPINGCAR_KEY%(user_id,course_id)
                course_obj = Course.objects.get(pk=course_id)
                course_info = json.loads(cache.get(shoppingcart_key))
                # 添加到结算字典中
                account_val["course_info"] = course_info

                # 获取优惠券信息,查看当前用户的当前课程的有效的未使用的优惠券
                coupons = self.get_coupon_dict(request,course_id)

                # 将优惠券字典添加到结算字典中
                account_val["coupons"] = coupons
                print("account_val:",account_val)

                cache.set(account_val,json.dumps(account_val))

            # 获取通用优惠券
            global_coupons = self.get_coupon_dict(request)
            cache.set("global_coupons_%s"%user_id,json.dumps(global_coupons))

            '''
                REDIS = {
                    account_userid_courseid = {
                        "course_info":course_info,
                        "coupons":{}
                    }   
                                     
                    account_userid_courseid = {
                        "course_info":course_info,
                        "coupons":{}
                    }
                    
                    global_coupons_userid:{
                        1:{}
                    }
                }
            '''



        except CommonExcetpion as e:
            res.code = e.code
            res.msg = e.msg

        except ObjectDoesNotExist as e:
            res.code = 1001
            res.msg = "课程不存在"

        return Response(res.dict)

    def get(self,request):
        res = BaseResponse()
        try:
            # 1.获取用户
            user_id = request.user.id
            # 2.拼接购物车key
            # shoppingcar_1_*
            shopping_car_key = settings.SHOPPINGCAR_KEY%(user_id,"*")

            # 3.去redis读取用户的所有加入购物车的课程
            # 3.1先去模糊匹配出所有符合要求的key

            all_keys = cache.keys(shopping_car_key)

            # all_keys = REDIS_CONN.scan_iter(shopping_car_key)
            print(all_keys)

            shopping_car_list = []
            for key in all_keys:
                print(key)
                course_info = json.loads(cache.get(key))
                print(course_info)
                shopping_car_list.append(course_info)

                res.data = {"shopping_car_list":shopping_car_list,"total":len(shopping_car_list)}

        except Exception as e:
            pass

        return Response(res.dict)

'''
{
	'course_info': {
		'title': 'Django课程',
		'img': 'https://hcdn1.luffycity.com/static/frontend/public_class/PY2@2x_1566529821.3087058.png',
		'relate_price_policy': {
			'4': {
				'pk': 4,
				'valid_period': 7,
				'valid_period_text': '1周',
				'price': 10.0,
				'default': False
			},
			'1': {
				'pk': 1,
				'valid_period': 14,
				'valid_period_text': '2周',
				'price': 30.0,
				'default': True
			},
			'5': {
				'pk': 5,
				'valid_period': 210,
				'valid_period_text': '12个月',
				'price': 12000.0,
				'default': False
			}
		},
		'choose_price_policy_id': 1,
		'price': 30.0,
		'valid_period': 14,
		'valid_period_text': '2周'
	},
	'coupons': {
		'1': {
			'name': '双十一百元立减券',
			'coupon_type': 0,
			'money_equivalent_value': 100.0,
			'off_percent': None,
			'minimum_consume': 0
		},
		'2': {
			'name': '双十二五折优惠券',
			'coupon_type': 2,
			'money_equivalent_value': 0.0,
			'off_percent': 50,
			'minimum_consume': 0
		}
	}
}

{
	'3': {
		'name': '51满减券',
		'coupon_type': 1,
		'money_equivalent_value': 50.0,
		'off_percent': None,
		'minimum_consume': 1000
	}
}
'''